//
//  CHGridView.swift
//  CertManageSdk
//
//  Created by cyptt on 2023/3/15.
//

import UIKit
public class CHGridView: UIView ,UICollectionViewDelegate{
   
    private let CELLID:String = "CHGridViewCollectCellID"
//    private var datas:[CHGridModel] = []
    private var rowMaxCount:Int = 3
    private var selfW:CGFloat = 300
    private var selfH:CGFloat = 100
    private var isShowView = false
    private var mItemSpacing:CGFloat = 0 //item间距
    private var mLineSpacing:CGFloat = 0 //行距
    private var mItemH:CGFloat? = nil  //高度是否固定
    private var colDataSource:CHGrideViewDataSource?

    private var viewModel:CHGrideViewModel?
    
    private var clickItemCallBack:((_ index:Int,_ gridModel:CHGridModel?) -> ())?
    private var cellSuccessCallBack:dataColSourceSuccessBlock?

    
    public override func awakeFromNib() {
        super.awakeFromNib()
        
        self.setUI()
        
    }
    public override init(frame: CGRect) {
        super.init(frame: frame)
        self.setUI()
    }
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    /*
     初始化
     @rowMaxCount 默认最大行个数3
     @itemSpacing 默认item间距0
     @lineSpacing 默认行间距0
     @itemH 高度固定
     */
    public init(rowMaxCount:Int? = 3,itemSpacing:CGFloat = 0,lineSpacing:CGFloat = 0,itemH:CGFloat? = nil) {
        super.init(frame: CGRect.zero)
        
        self.rowMaxCount = rowMaxCount!
        self.mItemSpacing = itemSpacing
        self.mLineSpacing = lineSpacing
        self.mItemH = itemH
        self.setUI()
    }
    private init(){
        super.init(frame: CGRect.zero)
    }
    
    func setUI(){
        
        weak var weakSelf = self
        self.isShowView = true;
        self.colDataSource = CHGrideViewDataSource(identifier: CELLID,successCallBack: { cell, model, indexPath, colectionView in
            let cell:CHGridViewColCell? = cell as? CHGridViewColCell
            let model:CHGridModel? = model as? CHGridModel
            let indexPath:IndexPath? = indexPath
            cell?.btn.setTitle(model?.title, for: .normal)
            let image:UIImage? = model?.iconImage
            
            cell?.btn.setImage(image, for: .normal)
            
            cell?.btn.setTitleColor(model?.titleColor, for: .normal)
            cell?.btn.titleLabel?.font = model?.titleFont
            cell?.backgroundColor = model?.cellBgColor
            
            var position:BUTTON_IMAGE_LOCAL_TYPE = .top
            if model?.imgPosition == .top{
                position = .top
            }else if model?.imgPosition == .left{
                position = .left
            }else if model?.imgPosition == .right{
                position = .right
            }else if model?.imgPosition == .bottom{
                position = .bottom
            }
            
            cell?.btn.imageLocal(local:position , margin: model?.margin ?? 10)
            
            if model?.cellHandelr != nil{
                model?.cellHandelr!(cell)
            }
            
          
            cell?.itemClickCallBack(clouse: { index in
                if weakSelf?.clickItemCallBack != nil {
                    weakSelf?.clickItemCallBack!(index,model)
                }
            }, index: indexPath?.row ?? 0)
        })
        
        
        
        
        self.viewModel = CHGrideViewModel.init(successBlock: { vModelResult in
            
            weakSelf?.colDataSource?.datas = vModelResult as! [Any]
            weakSelf?.collectView.reloadData()
        },failBlock: { vModelFailMsg in
            
        })
        
    }
    


    /*
     设置数据源
     */
    public func setDataSource(gridModels:[CHGridModel]){

     
        self.viewModel?.datas = gridModels
       
    }
    
    /*
     刷新数据
     */
    public func reloadData(){
  
        self.viewModel?.refreshData()
    }
    
    /*
     确定回调
     */
    public func itemClickCallBack(clouse:@escaping(_ index:Int,_ gridModel:CHGridModel?)-> Void){
        self.clickItemCallBack = clouse
    }
    
  
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        selfW = self.frame.size.width;
        selfH = self.frame.size.height;
        //保证只加载一次
        if (self.isShowView == true) {
            showView()
            self.reloadData()
        }
        
        self.isShowView = false;
 
        
    }
    
    
    
    func showView(){
        
      
        self.addSubview(self.collectView)
      
        self.collectView.register(CHGridViewColCell.self, forCellWithReuseIdentifier: CELLID)
    }
    
    
    
      lazy var collectView = {()-> UICollectionView in
          
        
          var rows  = 1 //多少行
          
          if self.viewModel != nil{
              if self.viewModel!.datas.count % self.rowMaxCount == 0{
                  rows = self.viewModel!.datas.count / self.rowMaxCount
              }else{
                  rows = (self.viewModel!.datas.count / self.rowMaxCount) + 1
              }
          }
        
          
          let contentW = selfW
          
          var contentH = selfH / CGFloat(rows)
        
       
          let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout.init()
          
          let allItemSpacings:CGFloat = self.mItemSpacing*CGFloat(self.rowMaxCount - 1) //间隙宽度总和
          let allLineSpacings:CGFloat = self.mLineSpacing * CGFloat(rows - 1) //间隙高度总和
          
          let  cellcontentW:CGFloat = contentW-allItemSpacings
          let cellContentH:CGFloat = selfH - allLineSpacings
          
          var itemH:CGFloat = cellContentH / CGFloat(rows)
          let itemW:CGFloat = cellcontentW/CGFloat(self.rowMaxCount)
          
          if self.mItemH != nil{
              itemH = self.mItemH!
          }
          
          layout.itemSize = CGSize.init(width: itemW, height: itemH)
          layout.minimumInteritemSpacing = self.mItemSpacing
          layout.minimumLineSpacing = self.mLineSpacing
        
        
          let rect:CGRect = CGRect.init(x: 0, y: 0, width: selfW, height: selfH);
          let collectView = UICollectionView.init(frame: rect, collectionViewLayout: layout)
         
          collectView.delegate = self
          collectView.dataSource = self.colDataSource
        
//          collectView.placeHolderDelegate = self
      
      
          collectView.backgroundColor = UIColor.clear
          if #available(iOS 11.0, *) {
      
              collectView.contentInsetAdjustmentBehavior = .never
          } else {
              // Fallback on earlier versions
          }
          
    
      
          return collectView
      }()
      

}


//MARK: --UICollectionViewDataSource
public extension CHGridView {
  
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    
        
        print("点击了")
      
    }
   
    

    
 
 
       
    
   
 
}


